﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GMS.DataAccessDapper;
using GMS.IServices;
using GMS.Models.Dto;
using GMS.Models.Entity;
using GMS.Utils;

namespace GMS.Services
{
    public class UserRolesService : IUserRolesService
    {
        private readonly DapperUtil _dapper;

        public UserRolesService(DapperUtil dapper)
        {
            _dapper = dapper;
        }

        /// <summary>
        /// TODO:这里数据应该使用缓存
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<UserRoles>> GetUserAllAsync(List<Guid> userIds)
        {
            string strSql = @"SELECT a.UserId,a.RoleId,b.Name as RoleName FROM dbo.User_Roles a
            INNER JOIN dbo.RoleInfo b ON a.RoleId = b.Id
            WHERE a.userId in @userIds";
            //List<Guid> userGuids = userIds.Split(",").ToList().ConvertAll<Guid>(x => x.ToGuid());
            return await _dapper.QueryMultipleAsync<UserRoles>(strSql, new { userIds });
        }

  

        public async Task<int> AddedAsync(UserRolesDto dto)
        {

            string strSql = "Delete from User_Roles where UserId=@userId";
            await _dapper.ExecuteAsync(strSql, new { dto.UserId });

            List<UserRoles> entities = new List<UserRoles>();
            var roles = dto.RoleIds.Split(",");

            foreach (var roleId in roles)
            {
                UserRoles entity = new UserRoles { UserId = dto.UserId, RoleId = roleId.ToGuid() };
                EntityHelper<UserRoles>.SetComm(entity);
                entities.Add(entity);
            }

            strSql = @"INSERT INTO dbo.User_Roles(UserId, RoleId,CreateId,CreateBy,CreateTime)
            VALUES(@userId, @roleId,@createId,@createBy,getdate())";
            return await _dapper.ExecuteAsync(strSql, entities);
        }

    }
}